package com.slipper.util;

import com.slipper.core.gson.GsonUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Random;

public class Tool {
    /**
     * 获取URL路径剔除前开始“/”，剔除“?”后的所的参数
     */
    public static String getRelativePath(HttpServletRequest request) {
        return Tool.getRelativePath(request.getServletPath());
    }

    /**
     * 获取URL路径剔除前开始“/”，剔除“?”后的所的参数
     */
    public static String getRelativePath(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }
        if (url.indexOf("?") > 0) {
            url = url.substring(0, url.indexOf("?"));
        }
        return url;
    }

    /**
     * 获取IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }

        if (ip.indexOf(",") > 0) {
            String[] ips = ip.split(",");
            for (String str : ips) {
                if (str != null && !str.trim().isEmpty()) {
                    ip = str.trim();
                    break;
                }
            }
        }
        return ip;
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean isBlank(Object ...objects) {
        for (Object object : objects) {
            if (object == null
                    || object.toString().trim().isEmpty()
                    || "null".equals(object.toString().trim())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isNotBlank(Object object) {
        return !(object == null
                || object.toString().trim().isEmpty()
                || "null".equals(object.toString().trim()));
    }

    public static String fillLength(int number, int length) {
        return fillLength(number + "", length, '0');
    }

    /**
     * 从左边开始填充字符串至特定长度
     */
    public static String fillLength(String str, int length, char c) {
        if (str != null && !str.isEmpty() && str.length() >= length) {
            return str;
        }
        return String.valueOf(c).repeat(Math.max(0, length - (str == null ? 0 : str.length())))
                + (str == null ? "" : str);
    }

    public static int randomNumber(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min) + min;
    }

    public static String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder returnStr = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            returnStr.append(str.charAt(random.nextInt(str.length())));
        }
        return returnStr.toString();
    }

    public static String randomHexString(int length) {
        String str = "0123456789abcdef";
        StringBuilder returnStr = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            returnStr.append(str.charAt(random.nextInt(str.length())));
        }
        return returnStr.toString();
    }

    public static byte[] toBytes(String s, String charset) throws UnsupportedEncodingException {
        if (s == null) {
            return new byte[] {};
        } else {
            return s.getBytes(charset);
        }
    }

    public static String concatPath(String path1, String path2) {
        if (path1 == null) {
            path1 = "";
        }
        if (path2 == null) {
            path2 = "";
        }
        if (path1.endsWith("/") && path2.startsWith("/")) {
            return path1.concat(path2.substring(1));
        } else if (path1.endsWith("/") || path2.startsWith("/")) {
            return path1.concat(path2);
        } else {
            return path1.concat("/").concat(path2);
        }
    }

    public static String substring(String str, int length) {
        if (isBlank(str) || str.length() < length) {
            return str;
        }
        return str.substring(0, length);
    }

    public static boolean isNumber(String str) {
        if (isBlank(str)) return false;

        str = str.trim();
        if (str.equals("0") || str.equals("0.")) return true;
        if (str.startsWith("0") && !str.startsWith("0.")) return false;
        return str.trim().matches("^(\\d+(\\.\\d+)?)$");
    }

    public static String computeIfAbsent(Object object, String value) {
        if (isBlank(object)) return value;
        return object.toString();
    }

    public static boolean isNotEmpty(Map<String, Object> result) {
        if (result == null || result.isEmpty()) return true;
        return result.values().stream().allMatch(Tool::isNotBlank);
    }

    public static String toJson(Object object) {
        return GsonUtil.toJson(object);
    }

    public static Map<String, Object> toMap(String json) {
        return GsonUtil.toMap(json);
    }

    public static String getUUID() {
        return UUID.getUUID();
    }

    public static String getUserHome() {
        String path = Tool.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        if (path.startsWith("file:")) {
            path = path.substring(5); // 去掉file:
        }
        path = new File(path).getParent();
        return path;
    }

    public static String split(String str, int length) {
        if (str == null || str.length() < length) return str;
        return str.substring(0, length);
    }
}
